import TableList from '@/components/TableList';
import {routeList, routeCreate, routeUpdate, routeDelete } from '@/pages/route/service';
import {PageContainer} from '@ant-design/pro-components';
import '@umijs/max';
import {message, Modal, Drawer} from "antd";
import FormModal from "@/components/FormModal";
import {useRef, useState} from "react";
import TOButton from "@/components/TableList/TOButton";
import TableOperations from "@/components/TableList/TableOperations";
import RouteForm from "@/pages/route/components/RouteForm";
import RouteMapMgr from './components/RouteMap';


const RouteMgr = () => {
  const [formModalVisible, setFormModalVisible] = useState(false);
  const [selectRecord, setSelectRecord] = useState(null);
  const [openRouteMap, setOpenRouteMap] = useState(false);
  const tableRef = useRef();
  const formRef = useRef();
  const {confirm} = Modal;

  const columns = [
    {
      title: '序号',
      align: 'center',
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 60,
    },
    {
      title: '路线名称',
      dataIndex: 'name',
      width: 100,
    },
    {
      title: '总点数',
      dataIndex: 'pointCount',
      width: 80,
    },
    {
      title: '最小速度',
      dataIndex: 'minVelocity',
      width: 100,
    },
    {
      title: '最大速度',
      dataIndex: 'maxVelocity',
      width: 100,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 180,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      align: 'center',
      fixed: 'right',
      width: 100,
      search: false,
      render: (_, record) => {
        const operations = [];
        operations.push(
          <TOButton
          key='map'
          type='primary'
          text='显示'
          onClick={() => {
            setSelectRecord(record)
            setOpenRouteMap(true)
            // setFormModalVisible(true)
          }}
        />
        );
        operations.push(<TOButton
          key='edit'
          type='primary'
          text='修改'
          onClick={() => {
            setSelectRecord(record)
            setFormModalVisible(true)
          }}
        />)

        operations.push(<TOButton
          key='del'
          type='danger'
          text='删除'
          onClick={() => {
            confirm({
              title: '删除路线',
              content: `是否删除“${record.code}”路线？`,
              async onOk() {
                await routeDelete({id: record.id});
                message.success('删除成功')
                tableRef.current.reload();
              }
            });
          }}
        />)
        return <TableOperations operations={operations} /> ;
      }
    }
  ];

  const addCallback = () => {
    if (selectRecord) setSelectRecord(null)
    setFormModalVisible(true)
  };

  return (
    <PageContainer>
      <TableList
        tableRef={tableRef}
        columns={columns}
        keyName="id"
        labelWidth={95}
        tableRequest={routeList}
        addCallback={addCallback}
        toolBarLeftArea="路线列表"
      />
      <FormModal
        title={`${selectRecord ? '修改' : '新增'}路线`}
        formRef={formRef}
        initFormValue={selectRecord || {isCheck: true, state: true}}
        visible={formModalVisible}
        onVisibleChange={visible => {
          setFormModalVisible(visible)
          if (!visible && selectRecord) {
            setSelectRecord(null)
          }
        }}
        labelCol={5}
        onConfirm={
          async (values) => {
            let request = selectRecord ? routeUpdate : routeCreate
            if (selectRecord) values.id = selectRecord.id
            values.state = values.state ? 1 : 0
            try {
              console.log('values', values)
              const file = values.upload[0].originFileObj
              delete values.upload
              const formData = new FormData();
              formData.append(
                "data",
                new Blob([JSON.stringify(values)], {
                  type: "application/json"
                })
              );
              formData.append("file", file);
              await request(formData)
              message.success('提交成功')
              tableRef.current.reload()
              return true
            } catch (e) {
              return false
            }
          }
        }
      >
        <RouteForm
          formRef={formRef}
          record={selectRecord}
        />
      </FormModal>
      
      <Drawer 
        destroyOnClose={true}
        title="路线地图" 
        width={1024} 
        closable={{ 'aria-label': 'Close Button' }} 
        open={openRouteMap} 
        onClose={() => {setOpenRouteMap(false)}} >

        <RouteMapMgr 
        record={selectRecord} 
        closeDrawer={() => {setOpenRouteMap(false)}}/>

      </Drawer>
      
    </PageContainer>
  );
};
export default RouteMgr;
